package com.online.realm;

import com.online.entity.User;
import com.online.service.UserService;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

public class UserRealm extends AuthorizingRealm {

    @Autowired
    UserService userService;

    //每次验证权限执行
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        //获取当前登录用户
        String workNumber =(String) principalCollection.getPrimaryPrincipal();
        //获取当前登录用户角色
        String role = userService.showRoleByUserBumber(workNumber);
        //添加用户角色
        info.addRole(role);
        return info;
    }

    //登录的时候执行
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        //获取用户登录userNumber
        String userNumber = (String) authenticationToken.getPrincipal();
        System.out.println(userNumber);
        User user = userService.showUserByUserNumber(userNumber);
        System.out.println(user.getUserNumber() + "" + user.getPassword());
        if (user != null) {
            return new SimpleAuthenticationInfo(userNumber, user.getPassword(), null, getName());
        }
        return null;
    }
}